package com.lkm.app_ui.help;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.LongSerializationPolicy;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.bind.ArrayTypeAdapter;
import com.google.gson.internal.bind.ObjectTypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

public class GsonHelp {

    public static Gson getGson() {

        return gson;
    }

    public final static Gson gson;

    static {

        GsonBuilder gsonBuilder = new GsonBuilder();


        gsonBuilder.serializeSpecialFloatingPointValues();

//     long到科学计数法的解决方法 。 System.out.println(new Gson().fromJson("{\"username\":\"tomcat\",\"uuid\":123456789012}",Map.class).get("uuid"));
        gsonBuilder.setLongSerializationPolicy(LongSerializationPolicy.STRING);


        gson = gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();

    }

    

    public final static JsonArray emptyJsonArray = new JsonArray();
    public final static JsonObject emptyJsonObject = new JsonObject();

    

    public static boolean isArrayJson(String json) {
        if (json == null)
            return false;
        return json.matches("^\\[.*\\]$");
    }

    public static JsonObject toJsonObject(Object object) {
        return toJsonObject(gson, object);
    }

    public static JsonObject toJsonObject(Gson gson, Object object) {
        if (object == null)
            return null;
        TypeAdapter oa = ObjectTypeAdapter.FACTORY.create(gson, TypeToken.get(Object.class));
        JsonObject hmJO = (JsonObject) oa.toJsonTree(object);
        return hmJO;
    }

    

    public static JsonArray toJsonArray(Object object) {
        return toJsonArray(gson, object);
    }

    

    public static JsonArray toJsonArray(Gson gson, Object object) {
        if (object == null)
            return null;
        TypeAdapter oa = ArrayTypeAdapter.FACTORY.create(gson, TypeToken.get(object.getClass()));
        JsonArray hmJO = (JsonArray) oa.toJsonTree(object);
        return hmJO;
    }

    public static <T> T fromJson(String json, Type classOfT) {
        return fromJson(gson, json, classOfT);
    }

    public static <T> T fromJson(JsonElement json, Type classOfT) {
        return gson.fromJson(json, classOfT);
    }

    

    @Deprecated
    public static JsonElement toJsonTree(String json) {
        return gson.toJsonTree(json);
    }

    

    public static <T> T fromJson(Gson gson, String json, Type classOfT) {
        try {
            return gson.fromJson(json, classOfT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toJson(Object src) {
        return gson.toJson(src);
    }
}
